package com.easymin.weixin.service.impl;

import com.easymin.weixin.entity.WxApplication;
import com.easymin.weixin.entity.WxApplicationCriteria;
import com.easymin.weixin.mapper.BaseMapper;
import com.easymin.weixin.mapper.WxApplicationMapper;
import com.easymin.weixin.service.WxApplicationService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class DefaultWxApplicationService extends AbstractBaseService<WxApplication, WxApplicationCriteria, Long> implements WxApplicationService {

  @Autowired
  private WxApplicationMapper wxApplicationMapper;

  @Override
  public BaseMapper<WxApplication, WxApplicationCriteria, Long> getMapper() {

    return wxApplicationMapper;
  }

  @Override
  public int insert(WxApplication wxApplication) {

    wxApplication.setCreated(new Date());
    wxApplication.setUpdated(new Date());
    wxApplication.setVersion(1);
    return super.insert(wxApplication);
  }

  @Override
  public WxApplication exists(String name) {

    WxApplicationCriteria criteria = new WxApplicationCriteria();
    criteria.createCriteria().andNameEqualTo(name);

    List<WxApplication> applications = wxApplicationMapper.selectByExample(criteria);

    if (!CollectionUtils.isEmpty(applications)) {
      return applications.get(0);
    }

    return null;
  }

  @Override
  public int update(WxApplication wxApplication) {

    wxApplication.setUpdated(new Date());
    return super.update(wxApplication);
  }

  @Override
  public WxApplication findByAppKey(String appKey) {

    WxApplicationCriteria wxApplicationCriteria = new WxApplicationCriteria();
    wxApplicationCriteria.createCriteria().andWxkeyEqualTo(appKey);

    List<WxApplication> applications = wxApplicationMapper.selectByExample(wxApplicationCriteria);

    if (!CollectionUtils.isEmpty(applications)) {
      return applications.get(0);
    }

    return null;
  }
  @Override
  public WxApplication findByAddress(String address) {
    
    WxApplicationCriteria wxApplicationCriteria = new WxApplicationCriteria();
    wxApplicationCriteria.createCriteria().andAddressEqualTo(address);
    
    List<WxApplication> applications = wxApplicationMapper.selectByExample(wxApplicationCriteria);
    
    if (!CollectionUtils.isEmpty(applications)) {
      return applications.get(0);
    }
    
    return null;
  }
}
